/*
 * Copyright 1999-2011 Alibaba Group.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dji.pa.cluster.db.dataSouce;

import java.util.List;
import java.util.Random;


/**
 *
 *加权随机算法-抄袭自dubbo--目前看起是我抄的有问题，需要改进
 */
public class RandomLoadBalance {

    private final Random random = new Random();

	protected Server doSelect(List<Server> invokers) {
		int length = invokers.size(); // 总个数
		int totalWeight = 0; // 总权重
		boolean sameWeight = true; // 权重是否都一样
		for (int i = 0; i < length; i++) {
			int weight = getWeight(invokers.get(i));
			totalWeight += weight; // 累计总权重
			if (sameWeight && i > 0 && weight != getWeight(invokers.get(i - 1))) {
				sameWeight = false; // 计算所有权重是否一样
			}
		}
		if (totalWeight > 0 && !sameWeight) {
			// 如果权重不相同且权重大于0则按总权重数随机
			int offset = random.nextInt(totalWeight);
			// 并确定随机值落在哪个片断上
			for (int i = 0; i < length; i++) {
				offset -= getWeight(invokers.get(i));
				if (offset < 0) {
					return invokers.get(i);
				}
			}
		}
		// 如果权重相同或权重为0则均等随机
		return invokers.get(random.nextInt(length));
	}

	protected int getWeight(Server invoker) {
		return invoker.getCurrentWeight();
	}
	public Server select(List<Server> invokers) {
		if (invokers == null || invokers.size() == 0)
			return null;
		if (invokers.size() == 1)
			return invokers.get(0);
		return doSelect(invokers);
	}

}